<?php
namespace jy_ailiao;
defined('BY_JYA') or exit('error');
/*
	服务中心分润计算	
*/
class fuwu extends \plugin{
	function register($post){
		$data=array(
				'title'=>$post['pcd']['city']?$post['pcd']['city'].'站':$post['title'],
				'pcd'=>ijson_encode($post['pcd']),
				'code'=>$post['code'],
				'address'=>$post['address'],
				'realname'=>$post['realname'],
				'mobile'=>$post['mobile'],
				'mid'=>$post['mid']?:$_SESSION['uid'],
				'status'=>$post['status'],
		);
		if($post['id']){
			pdo_update('jy_ailiao_fuwu',$data,array('id'=>$post['id']));
		}else{
			$data['uniacid']=$_SESSION['uniacid'];
			$data['createtime']=time();
			$this->insert('fuwu',$data);
		}
		return false;
	}
	/*
		审核区域代理
	*/
	public function check_agent($agent_id,$status,$remark=''){
		if(!$agent_id || !$status){
			return;
		}
		$agent_area=$this->get('fuwu',array('id'=>$agent_id));
		if(!$agent_area){
			return;
		}
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
		);
		if($update['status']==1){
		}else{
			$update['remark']=$remark;
		}
		$this->update('fuwu',$update,array('id'=>$agent_id));
		return true;
	}
	/*
		根据订单生成分润
	*/
	function create($order){
		$fuwuset=$this->plugin_setting('fuwuset');
		if(!$fuwuset['isopen']){
			return false;
		}
		$this->order=$order;		
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['money'],
			'commission_money'=>0,
			'createtime'=>TIMESTAMP,
		);
		$this->commission_order['commission_price']=$this->order['money'];
		$member=$this->get('member',array('mid'=>$this->order['mid'],'uniacid'=>$_SESSION['uniacid']));
		if(!$member['id']){
			$member=$this->model('member')->register();
		}
		$fuwu_id=$member['fuwu_id'];		
		$this->create_commission($fuwu_id);
		//生成分销订单
		$indata=$this->commission_order;
		unset($indata['isarea']);
		unset($indata['red_money']);
		$this->insert('order',$indata);
		return true;
	}
	/*
		红娘提现抽成
	*/
	function addhong_fee($order=array()){
		$fuwuset=$this->plugin_setting('fuwuset');
		if(!$fuwuset['isopen']){
			return '';
		}
		$worker=pdo_get('jy_ailiao_worker',array('mid'=>$order['mid'],'uniacid'=>$_SESSION['uniacid']));
		$fuwu=pdo_get('jy_ailiao_fuwu',array('id'=>$worker['fuwuid'],'uniacid'=>$_SESSION['uniacid']));
		if($fuwu['level_id']){
			$level=$this->get('fuwu_level',array('id'=>$fuwu['level_id'],'uniacid'=>$_SESSION['uniacid']));
		}else{
			$level=$this->plugin_setting('default_level');
		}
		$hong_per=$level['hong_per'];
		if(substr($hong_per,-1)=='%'){
			$money=($order['money']*substr($hong_per,0,-1))/100;
		}else{
			$money=$hong_per;
		}
		if($money>0){
			$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'fuwuid'=>$fuwu['id'],
					'level'=>$fuwu['level_id'],
					'orderid'=>$order['id'],
					'money'=>$money,
					'commission_type'=>3,
					'createtime'=>TIMESTAMP,
					'status'=>1,
			);
			$this->insert('commission',$new_commission);
		}
		return true;
	}
	/*
		客户提现抽成
	*/
	function addtohong_fee($order=array()){
		$fuwuset=$this->plugin_setting('fuwuset');
		if(!$fuwuset['isopen'] || !$fuwuset['tohong_per']){
			return '';
		}
		$member=pdo_get('jy_ailiao_member',array('mid'=>$order['mid'],'uniacid'=>$_SESSION['uniacid']));
		if(!$member['worker_id']){
			return '';
		}
		$worker=pdo_get('jy_ailiao_worker',array('id'=>$member['worker_id'],'uniacid'=>$_SESSION['uniacid']));
		if(!$worker['mid']){
			return '';
		}
		$hong_per=$fuwuset['tohong_per'];
		if(substr($hong_per,-1)=='%'){
			$money=($order['money']*substr($hong_per,0,-1))/100;
		}else{
			$money=$hong_per;
		}
		if($money>0){
			$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'fuwuid'=>$member['fuwu_id'],
					'mid'=>$worker['mid'],
					'orderid'=>$order['id'],
					'money'=>$money,
					'commission_type'=>4,
					'createtime'=>TIMESTAMP,
					'status'=>2,
			);
			$this->insert('commission',$new_commission);
			model('core/member')->member_credit($worker['mid'],'credit2',$money,true,'jy_ailiao','客户提现抽成');
		}
		return true;
	}
	/*
		给指定服务中心计算分红
	*/
	public function create_commission($fuwu_id){
			if(!$fuwu_id){
				return false;
			}
			$fuwu=pdo_get('jy_ailiao_fuwu',array('id'=>$fuwu_id));
			if($fuwu['level_id']){
				$level=pdo_get('jy_ailiao_fuwu_level',array('id'=>$fuwu['level_id']));
			}else{
				$level=$this->plugin_setting('default_level');
			}
			$commission_per=$level['fee_per'];
			if(substr($commission_per,-1)=='%'){
				$commission_per=substr($commission_per,0,-1);
				$commission_money=($this->order['money']*$commission_per)/100;
			}else{
				$commission_money=$commission_per;
			}
			$remark=array(
				'level_id'=>$fuwu['level_id'],
				'order_price'=>$this->order['money'],
				'commission_money'=>$commission_money,
				'commission_per'=>$commission_per,
				'goods_commission'=>array(
					array('total_price'=>$this->order['money'],'total'=>1,'commission_per'=>$commission_per,'commission_money'=>$commission_money),
				),
			);
			$new_commission=array(
				'uniacid'=>$_SESSION['uniacid'],
				'fuwuid'=>$fuwu_id,
				'level'=>$fuwu['level_id'],
				'orderid'=>$this->order['id'],
				'money'=>$commission_money,
				'remark'=>ijson_encode($remark),
				'commission_type'=>1,
				'createtime'=>TIMESTAMP,
				'status'=>1,
			);
			$this->insert('commission',$new_commission);
			$this->update_agent_level($fuwu_id);
	}
	public function current_level_up_types(){
		$fuwuset=$this->plugin_setting('fuwuset');
		return str_array($fuwuset['level_up_types']);
	}
	public function update_agent_level($fuwu_id){
		$fuwu=$this->get('fuwu',array('id'=>$fuwu_id));
		if($fuwu['stop']){
			return;
		}
		$level=pdo_getcolumn('jy_ailiao_fuwu_level',array('id'=>$fuwu['level_id']),'level');
		$levels=$this->getall('fuwu_level',array('uniacid'=>$_SESSION['uniacid'],'level >'=>$level));
		if(!$levels){
			return;
		}
		$up=false;
		$level_up_types=$this->current_level_up_types();//获取当前设置的分销商等级升级条件
		if(!$level_up_types){
			return;
		}
		foreach($levels as $lv){
			$conditions=json_decode($lv['conditions'],true);
			$up=true;
			foreach($level_up_types as $type){
				if($type=='order_price'){
					$ordermoney=pdo_getsum('jy_ailiao_order',array('fuwuid'=>$fuwuid),'order_price');
					if($ordermoney<$conditions['order_price'] && $conditions['order_price']){
						$next_level=$lv;
						$up=false;
						continue;
					}
				}
				if($type=='order_num'){
					$order_num=pdo_count('jy_ailiao_order',array('fuwuid'=>$fuwuid),'id');
					if($order_num<$conditions['order_num'] && $conditions['order_num']){
						$up=false;
						continue;
					}
				}
				if($up){
					$next_level=$lv;
					break;
				}
			}
		}
		if($up){
			$update=array(
				'level_id'=>$next_level['id'],
			);
			$this->update('fuwu',$update,array('id'=>$fuwu_id));
		}
		return true;
	}
	/*
		创建结算单
	*/
	public function create_balance($fuwuid,$post=array()){
		if(!$fuwuid){
			exi('请先选择要结算的服务站！','error');
		}
		if($post['pay_type']=='downline'){
			if(!$post['wechat']){
				exi('请先填写微信号！','error');
			}
			if(!$post['mobile']){
				exi('请先填写联系电话！','error');
			}
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		//获取可结算分润
		$params=array('uniacid'=>$_SESSION['uniacid'],'fuwuid'=>$fuwuid,'status'=>1);
		if($this->zhaoshang['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->zhaoshang['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的分润！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低分润检测
		if($money<1){
			exi('可结算分润太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'fuwuid'=>$fuwuid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'wechat'=>$post['wechat'],
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->zhaoshang['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->zhaoshang['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销分润打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn){
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'代理商分润发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，分润比例【{$goods['commission_per']}%】，分销分润【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='未启用';
		}
		$remark['level_title']=pdo_getcolumn('jy_merch_level',array('id'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
服务中心等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，订单总价【{$remark['order_price']}】
商品独立分润：
{$goods_str}
分润总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}